package co.yixiang.yshop.module.crm.dal.mysql.crmclues;

import co.yixiang.yshop.framework.common.pojo.PageResult;
import co.yixiang.yshop.framework.mybatis.core.mapper.BaseMapperX;
import co.yixiang.yshop.framework.mybatis.core.query.LambdaQueryWrapperX;
import co.yixiang.yshop.framework.security.core.util.SecurityFrameworkUtils;
import co.yixiang.yshop.module.crm.controller.admin.crmclues.vo.CrmCluesPageReqVO;
import co.yixiang.yshop.module.crm.controller.admin.crmclues.vo.CrmCluesRespVO;
import co.yixiang.yshop.module.crm.dal.dataobject.crmclues.CrmCluesDO;
import co.yixiang.yshop.module.crm.enums.CluesStatusEnum;
import co.yixiang.yshop.module.system.dal.dataobject.user.AdminUserDO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.session.ResultHandler;

import java.util.ArrayList;
import java.util.List;

/**
 * 线索 Mapper
 *
 * @author yshop
 */
@Mapper
public interface CrmCluesMapper extends BaseMapperX<CrmCluesDO> {

    /**
     * 常规分页查询线索列表，不支持多负责人查询
     * 根据登录用户角色筛选所管理的线索
     *
     * @param reqVO 查询条件
     * @param ids 根据角色过滤的用户ID列表
     * @return 符合条件的线索分页结果
     */
    default PageResult<CrmCluesRespVO> selectPage(CrmCluesPageReqVO reqVO, List<Long> ids) {
        MPJLambdaWrapper<CrmCluesDO> wrapper = new MPJLambdaWrapper<>();
        wrapper.selectAll(CrmCluesDO.class)
                .selectAs(AdminUserDO::getNickname, CrmCluesRespVO::getOwnUserName)
                .leftJoin(AdminUserDO.class, AdminUserDO::getId, CrmCluesDO::getOwnerUserId);

        // 记录查询参数
        System.out.println("selectPage - 标准查询接口");
        System.out.println("- ids: " + ids);
        System.out.println("- ownerUserId: " + reqVO.getOwnerUserId());

        // 关键修改：排除公海线索（status=-1）
        wrapper.ne(CrmCluesDO::getStatus, CluesStatusEnum.STATUS_NEG_1.getValue());

        // 单个负责人筛选 or 根据角色权限筛选
        boolean hasOwnerFilter = false;
        
        // 1. 检查是否有指定的单个负责人ID查询
        if (reqVO.getOwnerUserId() != null) {
            wrapper.eq(CrmCluesDO::getOwnerUserId, reqVO.getOwnerUserId());
            hasOwnerFilter = true;
            System.out.println("应用单个 ownerUserId 筛选: " + reqVO.getOwnerUserId());
        }
        
        // 2. 没有指定负责人时，根据角色权限过滤
        if (!hasOwnerFilter && ids != null && !ids.isEmpty()) {
            wrapper.in(CrmCluesDO::getOwnerUserId, ids);
            System.out.println("应用角色权限 ids 筛选: " + ids);
        }

        // 其他筛选条件
        applyCommonFilters(reqVO, wrapper);

        return selectJoinPage(reqVO, CrmCluesRespVO.class, wrapper);
    }

    /**
     * 导出功能专用查询方法，支持多负责人查询
     *
     * @param reqVO 查询条件，包含ownerUserIds字段允许多负责人查询
     * @return 符合条件的线索分页结果
     */
    default PageResult<CrmCluesRespVO> selectExportPage(CrmCluesPageReqVO reqVO) {
        MPJLambdaWrapper<CrmCluesDO> wrapper = new MPJLambdaWrapper<>();
        wrapper.selectAll(CrmCluesDO.class)
                .selectAs(AdminUserDO::getNickname, CrmCluesRespVO::getOwnUserName)
                .leftJoin(AdminUserDO.class, AdminUserDO::getId, CrmCluesDO::getOwnerUserId);

        // 记录查询参数
        System.out.println("selectExportPage - 导出查询接口");
        System.out.println("- ownerUserIds: " + reqVO.getOwnerUserIds());
        System.out.println("- ownerUserId: " + reqVO.getOwnerUserId());

        // 关键修改：排除公海线索（status=-1），除非明确指定查询status=-1
        if (reqVO.getStatus() == null || !CluesStatusEnum.STATUS_NEG_1.getValue().equals(reqVO.getStatus())) {
            wrapper.ne(CrmCluesDO::getStatus, CluesStatusEnum.STATUS_NEG_1.getValue());
        }
        
        // 处理负责人ID筛选 - 优先级: ownerUserIds > ownerUserId
        boolean hasOwnerFilter = false;
        
        // 1. 首先检查是否有 ownerUserIds (多负责人)
        if (reqVO.getOwnerUserIds() != null && !reqVO.getOwnerUserIds().isEmpty()) {
            String[] idStrArray = reqVO.getOwnerUserIds().split(",");
            List<Long> ownerIds = new ArrayList<>();
            for (String idStr : idStrArray) {
                try {
                    ownerIds.add(Long.parseLong(idStr.trim()));
                } catch (NumberFormatException e) {
                    // Skip invalid IDs
                }
            }
            if (!ownerIds.isEmpty()) {
                wrapper.in(CrmCluesDO::getOwnerUserId, ownerIds);
                hasOwnerFilter = true;
                System.out.println("应用多个 ownerUserIds 筛选: " + ownerIds);
            }
        }
        
        // 2. 如果没有多负责人筛选，检查单个负责人
        if (!hasOwnerFilter && reqVO.getOwnerUserId() != null) {
            wrapper.eq(CrmCluesDO::getOwnerUserId, reqVO.getOwnerUserId());
            System.out.println("应用单个 ownerUserId 筛选: " + reqVO.getOwnerUserId());
        }

        // 其他筛选条件
        applyCommonFilters(reqVO, wrapper);

        return selectJoinPage(reqVO, CrmCluesRespVO.class, wrapper);
    }

    /**
     * 专门查询公海线索，即状态为-1的线索
     * 并确保一个线索只会出现在同一部门的用户视图中
     *
     * @param reqVO 分页查询条件
     * @return 公海线索分页结果
     */
    default PageResult<CrmCluesRespVO> selectPublicSeaPage(CrmCluesPageReqVO reqVO) {
        MPJLambdaWrapper<CrmCluesDO> wrapper = new MPJLambdaWrapper<>();
        wrapper.selectAll(CrmCluesDO.class)
                .selectAs(AdminUserDO::getNickname, CrmCluesRespVO::getCreateName)
                .leftJoin(AdminUserDO.class, AdminUserDO::getId, CrmCluesDO::getCreator);

        // 记录查询条件
        System.out.println("公海线索查询 - selectPublicSeaPage 执行，请求参数: " + reqVO);
                
        // 公海线索的核心条件：状态为-1
        wrapper.eq(CrmCluesDO::getStatus, CluesStatusEnum.STATUS_NEG_1.getValue());
        
        // 部门过滤 - 获取当前登录用户的部门ID
        Long currentUserDeptId = SecurityFrameworkUtils.getLoginUserDeptId();
        System.out.println("当前用户部门ID: " + currentUserDeptId);
        
        if (currentUserDeptId != null) {
            // 创建子查询，查找与当前用户同部门的所有用户ID
            wrapper.inSql(CrmCluesDO::getOwnerUserId, 
                "SELECT id FROM system_users WHERE dept_id = " + currentUserDeptId);
            System.out.println("应用部门过滤条件: 只查看同部门用户放入公海的线索");
        }

        // 添加其他筛选条件
        applyCommonFilters(reqVO, wrapper);
        
        return selectJoinPage(reqVO, CrmCluesRespVO.class, wrapper);
    }

    /**
     * 应用通用的筛选条件
     * 
     * @param reqVO 查询请求参数
     * @param wrapper 查询条件构造器
     */
    default void applyCommonFilters(CrmCluesPageReqVO reqVO, MPJLambdaWrapper<CrmCluesDO> wrapper) {
        if (reqVO.getName() != null) {
            wrapper.like(CrmCluesDO::getName, reqVO.getName());
        }
        if (reqVO.getMobile() != null) {
            wrapper.eq(CrmCluesDO::getMobile, reqVO.getMobile());
        }
        if (reqVO.getTelephone() != null) {
            wrapper.eq(CrmCluesDO::getTelephone, reqVO.getTelephone());
        }
        if (reqVO.getStatus() != null) {
            wrapper.eq(CrmCluesDO::getStatus, reqVO.getStatus());
        }
        if (reqVO.getLevel() != null) {
            wrapper.eq(CrmCluesDO::getLevel, reqVO.getLevel());
        }
        if (reqVO.getSource() != null) {
            wrapper.eq(CrmCluesDO::getSource, reqVO.getSource());
        }
        if (reqVO.getIndustry() != null) {
            wrapper.eq(CrmCluesDO::getIndustry, reqVO.getIndustry());
        }
        
        if (reqVO.getOwnerUserName() != null) {
            wrapper.like(AdminUserDO::getNickname, reqVO.getOwnerUserName());
        }
        if (reqVO.getCustomerId() != null) {
            wrapper.eq(CrmCluesDO::getCustomerId, reqVO.getCustomerId());
        }
        if (reqVO.getProvince() != null) {
            wrapper.eq(CrmCluesDO::getProvince, reqVO.getProvince());
        }
        if (reqVO.getCity() != null) {
            wrapper.eq(CrmCluesDO::getCity, reqVO.getCity());
        }
        if (reqVO.getArea() != null) {
            wrapper.eq(CrmCluesDO::getArea, reqVO.getArea());
        }
        if (reqVO.getDetailAddress() != null) {
            wrapper.like(CrmCluesDO::getDetailAddress, reqVO.getDetailAddress());
        }
        if (reqVO.getTags() != null) {
            wrapper.like(CrmCluesDO::getTags, reqVO.getTags());
        }
        if (reqVO.getRemark() != null) {
            wrapper.like(CrmCluesDO::getRemark, reqVO.getRemark());
        }
        if (reqVO.getChannelSource() != null) {
            wrapper.like(CrmCluesDO::getChannelSource, reqVO.getChannelSource());
        }
        if (reqVO.getSex() != null) {
            wrapper.like(CrmCluesDO::getSex, reqVO.getSex());
        }
        if (reqVO.getAge() != null) {
            wrapper.like(CrmCluesDO::getAge, reqVO.getAge());
        }
        if (reqVO.getMarried() != null) {
            wrapper.like(CrmCluesDO::getMarried, reqVO.getMarried());
        }
        if (reqVO.getEducation() != null) {
            wrapper.like(CrmCluesDO::getEducation, reqVO.getEducation());
        }
        if (reqVO.getHeight() != null) {
            wrapper.eq(CrmCluesDO::getHeight, reqVO.getHeight());
        }
        if (reqVO.getWeight() != null) {
            wrapper.eq(CrmCluesDO::getWeight, reqVO.getWeight());
        }
        if (reqVO.getRemarks() != null) {
            wrapper.like(CrmCluesDO::getRemarks, reqVO.getRemarks());
        }
        if (reqVO.getIncome() != null) {
            wrapper.eq(CrmCluesDO::getIncome, reqVO.getIncome());
        }
        if (reqVO.getRegisterTime() != null && reqVO.getRegisterTime().length == 2) {
            wrapper.between(CrmCluesDO::getRegisterTime, reqVO.getRegisterTime()[0], reqVO.getRegisterTime()[1]);
        }
        if (reqVO.getFollowRecords() != null) {
            wrapper.like(CrmCluesDO::getFollowRecords, reqVO.getFollowRecords());
        }
        if (reqVO.getUserName() != null) {
            wrapper.like(CrmCluesDO::getUserName, reqVO.getUserName());
        }
        if (reqVO.getDealStatus() != null) {
            wrapper.like(CrmCluesDO::getDealStatus, reqVO.getDealStatus());
        }
        if (reqVO.getCluesLevel() != null) {
            wrapper.like(CrmCluesDO::getCluesLevel, reqVO.getCluesLevel());
        }
        if (reqVO.getWechat() != null) {
            wrapper.like(CrmCluesDO::getWechat, reqVO.getWechat());
        }
        if (reqVO.getQq() != null) {
            wrapper.like(CrmCluesDO::getQq, reqVO.getQq());
        }
        if (reqVO.getChangeTime() != null && reqVO.getChangeTime().length == 2) {
            wrapper.between(CrmCluesDO::getChangeTime, reqVO.getChangeTime()[0], reqVO.getChangeTime()[1]);
        }
        if (reqVO.getNextTime() != null && reqVO.getNextTime().length == 2) {
            wrapper.between(CrmCluesDO::getNextTime, reqVO.getNextTime()[0], reqVO.getNextTime()[1]);
        }
        if (reqVO.getFollowTime() != null && reqVO.getFollowTime().length == 2) {
            wrapper.between(CrmCluesDO::getFollowTime, reqVO.getFollowTime()[0], reqVO.getFollowTime()[1]);
        }
        if (reqVO.getCollectTime() != null && reqVO.getCollectTime().length == 2) {
            wrapper.between(CrmCluesDO::getCollectTime, reqVO.getCollectTime()[0], reqVO.getCollectTime()[1]);
        }
        if (reqVO.getCreateTime() != null && reqVO.getCreateTime().length == 2) {
            wrapper.between(CrmCluesDO::getCreateTime, reqVO.getCreateTime()[0], reqVO.getCreateTime()[1]);
        }
        if (reqVO.getUpdateTime() != null && reqVO.getUpdateTime().length == 2) {
            wrapper.between(CrmCluesDO::getUpdateTime, reqVO.getUpdateTime()[0], reqVO.getUpdateTime()[1]);
        }
        if (reqVO.getAssignTime() != null && reqVO.getAssignTime().length == 2) {
            wrapper.between(CrmCluesDO::getAssignTime, reqVO.getAssignTime()[0], reqVO.getAssignTime()[1]);
        }
        if (reqVO.getFollowStatus() != null) {
            wrapper.eq(CrmCluesDO::getFollowStatus, reqVO.getFollowStatus());
        }
        
        // 排序
        wrapper.orderByDesc(CrmCluesDO::getAssignTime);
        wrapper.orderByDesc(CrmCluesDO::getCreateTime);
    }
}

